package com.lqian;

import com.lqian.pojo.Catalog;
import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * @author：Melody_LQ
 * @time：2022/8/19 11:53 上午
 */
public class T1 {

    @Test
    public void test1() throws Exception {
        //声明一个空的Optional
        Optional<Object> empty = Optional.empty();

        //依据一个非空值创建Optional
        Catalog catalog = new Catalog();
        Optional<Catalog> oc1 = Optional.of(catalog);
        //判断Optional容器中是否包含对象
        boolean present = oc1.isPresent();
        System.out.println("是否为空"+ present);
        Optional.ofNullable(catalog).ifPresent(p ->p.setName("jack"));
        System.out.println(oc1);

        //可接受null的Optional
        Catalog catalog1 = null;
        Optional<Catalog> oc2 = Optional.ofNullable(catalog1);

        //使用get一定要注意，假如catalog1为null，get是会报错的
        //Catalog catalog2 = oc2.get(); //java.util.NoSuchElementException: No value present

        //解决： orElse 当catalog1为空的时候，返回我们创建的这个对象
        Catalog catalog3 = oc2.orElse(new Catalog(1, "iphone 13", 1, 1));
        System.out.println(catalog3); //Catalog(id=1, name=iphone 13, browseCount=1, version=1)

        // orElseGet 当catalog1为空的时候，返回Supplier供应商函数创建的对象
        //Catalog(id=2, name=iphone 14, browseCount=1, version=1)
        System.out.println(oc2.orElseGet(() -> (new Catalog(2, "iphone 14", 1, 1))));

        //orElseThrow 如果Catalog 为空，可以抛出指定异常
        //java.lang.Exception: Catalog is null!
        oc2.orElseThrow(()->new Exception("Catalog is null!"));
    }

    @Test
    public void m2(){
        Map<String,Object> testMap = new HashMap();
        testMap.put(null, null);
//        testMap.forEach((k,v)->{
//            System.out.println(k + "--" +v);
//        });
        Iterator<String> iterator = testMap.keySet().iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }


    }

}
